﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace TestJsonPRICH
{
    public class FxConfigProvider : FileConfigurationProvider
    {

        public FxConfigProvider(FxConfigSource source) : base(source)
        {

        }

        public override void Load(Stream stream)
        {
            if (stream == null)
            {
                return;
            }
            var data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(stream);
            XmlNodeList nodeList = xmlDoc.SelectNodes("/configuration/connectionStrings/add");
            if (nodeList != null)
            {
                foreach (XmlNode itemNode in nodeList)
                {
                    if (itemNode == null)
                    {
                        continue;
                    }
                    string name = itemNode.Attributes["name"].Value;
                    string conn = itemNode.Attributes["connectionString"].Value;
                    data[$"{name}:name"] = name;
                    data[$"{name}:connectionString"] = conn;
                    var providerNameObj = itemNode.Attributes["providerName"];
                    if (providerNameObj != null)
                    {
                        string providerName = providerNameObj.Value;
                        data[$"{name}:providerName"] = providerName;
                    }
                }
            }

            XmlNodeList appnodeList = xmlDoc.SelectNodes("/configuration/appSettings/add");
            if (appnodeList != null)
            {
                foreach (XmlNode itemNode in appnodeList)
                {
                    if (itemNode == null)
                    {
                        continue;
                    }
                    var keyObj = itemNode.Attributes["key"];
                    var valObj = itemNode.Attributes["value"];

                    if (keyObj != null && valObj != null)
                    {
                        data[$"{keyObj.Value}:key"] = keyObj.Value;
                        data[$"{keyObj.Value}:value"] = valObj.Value;
                    }

                }
            }

            this.Data = data;
        }
    }
}
